package cn.operation.backend.service.baseBrand;


import cn.operation.backend.bo.CvBrandBO;
import cn.operation.backend.bo.ScBaseCvBrandBO;
import cn.operation.backend.bo.baseBrand.ScBrandSeriesModelBo;
import cn.operation.backend.enums.BaseStatusEnum;
import cn.operation.backend.enums.StatusEnum;
import cn.operation.backend.query.BrandQueryConditions;
import cn.operation.backend.util.BusinessException;
import cn.operation.backend.util.PageVo;
import cn.operation.backend.util.ResultDTOWithPagination;
import cn.operation.backend.util.pinyinUtil;
import cn.operation.base.dto.extdto.baseBrand.ScBaseCvBrandDto;
import cn.operation.base.mapper.ScBaseCvBrandMapper;
import cn.operation.base.mapper.extmapper.baseBrand.ScBaseBrandExpandMapper;
import cn.operation.base.model.BrandSeriesModel;
import cn.operation.base.model.ScBaseCvBrand;
import cn.operation.base.model.ScBaseCvBrandExample;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.*;

@Service
public class ScBaseCvBrandServiceImpl implements ScBaseCvBrandService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ScBaseCvBrandServiceImpl.class);

	@Autowired
	ScBaseBrandExpandMapper scBaseBrandExpandMapper;

	@Autowired
	private ScBaseCvBrandMapper scBaseCvBrandMapper;

	@Override
	public Integer add(CvBrandBO form, BindingResult br) throws Exception {
		LOGGER.info("BrandServiceImpl.add params : {}", form);

		if (null == form) {
			LOGGER.error("SeriesServiceImpl.add param form must not be null ");
			throw new IllegalArgumentException("数据不能为空");
		}

		// 验证表单
		verificationForm(br);

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationCodeUnique(form);

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationNameUnique(form);

		ScBaseCvBrand scBaseCvBrand = new ScBaseCvBrand();
		BeanUtils.copyProperties(form, scBaseCvBrand);

		scBaseCvBrandMapper.insertSelective(scBaseCvBrand);

		return scBaseCvBrand.getId();
	}

	@Override
	public ScBaseCvBrand selectById(Integer id) {
		LOGGER.info("BrandServiceImpl.selectById param : {}", id);

		if (id == null) {
			LOGGER.error("BrandServiceImpl.selectById param Code must not be null ");
			throw new IllegalArgumentException("ID不能为空");
		}
		return scBaseCvBrandMapper.selectByPrimaryKey(id);
	}

	@Override
	public Integer update(CvBrandBO form, BindingResult br) throws Exception {
		LOGGER.info("BrandServiceImpl.update params : {}", form);
		if (null == form) {
			LOGGER.error("BrandServiceImpl.update param form must not be null ");
			throw new IllegalArgumentException("不能为空");
		}

		// 验证表单
		verificationForm(br); // 改在Controller验证

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationCodeUnique(form);

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationNameUnique(form);

		ScBaseCvBrand scBaseCvBrand = new ScBaseCvBrand();
		BeanUtils.copyProperties(form, scBaseCvBrand);

		scBaseCvBrandMapper.updateByPrimaryKeySelective(scBaseCvBrand);

		return scBaseCvBrand.getId();
	}

	@Override
	public int deleteBatch(List ids) throws Exception {
		LOGGER.info("BrandServiceImpl.updateCodeGroup params : {}", ids);
		if (null == ids || ids.size() < 1) {
			LOGGER.error("BrandServiceImpl.deleteCodeGroupBatch param form must not be null ");
			throw new IllegalArgumentException("数据不能为空");
		}
		return scBaseCvBrandMapper.batchDelete(ids);
	}

	@Override
	public ResultDTOWithPagination selectListByConditions(PageVo pageVo, BrandQueryConditions conditions) {
		LOGGER.info("BrandServiceImpl.selectListByConditions params : {}, {}", pageVo, conditions);

		if (null == conditions) {
			LOGGER.error("BrandServiceImpl.selectCodeGroupListByConditions param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}



		String orderByClause = null;
		if (null != pageVo) {
			orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
		}

		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		ScBaseCvBrandExample.Criteria criteria = example.createCriteria();

		if (StringUtils.isNotBlank(conditions.getPrefix())) {
			criteria.andPrefixEqualTo(conditions.getPrefix());
		}
		if (StringUtils.isNotBlank(conditions.getName())) {
			criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
		}

		criteria.andStatusNotEqualTo(StatusEnum.DELETE.getValue());

		if (null != pageVo) {
			pageVo.setTotalRecord(scBaseCvBrandMapper.countByExample(example));
			example.setLimitStart(pageVo.getStartIndex());
			example.setLimitEnd(pageVo.getPageSize());
			example.setOrderByClause(orderByClause);
		}

		List<ScBaseCvBrand> list = scBaseCvBrandMapper.selectByExample(example);
		// 根据key去七牛获取url返回
		// String logoUrl=
		// QiniuUtil.generateDownloadURL(list.get(i).getBrandLogoUrl(),"1");
		ResultDTOWithPagination result = new ResultDTOWithPagination<>(true, null, "查询成功");

		result.setData(list);

		if (null != pageVo) {
			result.setPageVo(pageVo);
		}

		return result;
	}

	public void verificationForm(BindingResult br) {

		if (null == br) {
			LOGGER.error("BrandServiceImpl.verificationForm error br is null");
			throw new IllegalArgumentException("BindingResult is null");
		}

		if (br.hasErrors()) {
			List<ObjectError> list = br.getAllErrors();
			LOGGER.error("BrandServiceImpl.add error : {}", list.get(0).getDefaultMessage());
			throw new IllegalArgumentException(list.get(0).getDefaultMessage());
		}
	}

	public void verificationCodeUnique(CvBrandBO form) throws Exception {
		LOGGER.info("BrandServiceImpl.verificationCodeUnique params : {}, {}", form);

		if (form.getCode() == null) {
			LOGGER.error("BrandServiceImpl.verificationUnique param form must not be null");
			throw new IllegalArgumentException("品牌编码不能为空");
		}

		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		example.createCriteria().andCodeEqualTo(form.getCode());
		example.createCriteria().andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		List<ScBaseCvBrand> list = scBaseCvBrandMapper.selectByExample(example);

		if (list!=null&&list.size()>0) {

			ScBaseCvBrand scBaseCvBrand = list.get(0);

			// 修改时判断 如果id一致则修改时未改变
			if (form.getId() != null && form.getId().equals(scBaseCvBrand.getId())) {
				return;
			}
			LOGGER.error("BrandServiceImpl.verificationCodeUnique error list is not empty");
			throw new BusinessException("品牌编码已存在！");
		}
	}

	public void verificationNameUnique(CvBrandBO form) throws Exception {
		LOGGER.info("BrandServiceImpl.verificationNameUnique params : {}, {}", form);

		if (form.getName() == null) {
			LOGGER.error("BrandServiceImpl.verificationNameUnique param form must not be null");
			throw new IllegalArgumentException("品牌名称不能为空");
		}

		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		example.createCriteria().andNameEqualTo(form.getName());
		example.createCriteria().andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		List<ScBaseCvBrand> list = scBaseCvBrandMapper.selectByExample(example);

		if (list!=null&&list.size()>0) {

			ScBaseCvBrand scBaseCvBrand = list.get(0);

			// 修改时判断 如果id一致则修改时未改变
			if (form.getId() != null && form.getId().equals(scBaseCvBrand.getId())) {
				return;
			}
			LOGGER.error("BrandServiceImpl.verificationNameUnique error list is not empty");
			throw new BusinessException("品牌名称已存在！");
		}

	}

	@Override
	public List<ScBaseCvBrand> getAllList(PageVo pageVo, BrandQueryConditions conditions) throws Exception {
		LOGGER.info("BrandServiceImpl.getAllList params : {}, {}", pageVo, conditions);

		if (null == conditions) {
			LOGGER.error("SeriesServiceImpl.getAllList param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}

		try {
			String orderByClause = null;
			if (null != pageVo) {
				orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
			}

			ScBaseCvBrandExample example = new ScBaseCvBrandExample();
			ScBaseCvBrandExample.Criteria criteria = example.createCriteria();

			if (StringUtils.isNotBlank(conditions.getPrefix())) {
				criteria.andPrefixEqualTo(conditions.getPrefix());
			}

			if (StringUtils.isNotBlank(conditions.getName())) {
				criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
			}

			if (null != conditions.getId() && conditions.getId() > 0) {
				criteria.andIdEqualTo(conditions.getId());
			}

			if (null != conditions.getCode() && StringUtils.isNotBlank(conditions.getCode())) {
				criteria.andCodeEqualTo(conditions.getCode());
			}

			criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());

			if (null != pageVo) {
				pageVo.setTotalRecord(scBaseCvBrandMapper.countByExample(example));
				example.setLimitStart(pageVo.getStartIndex());
				example.setLimitEnd(pageVo.getPageSize());
				example.setOrderByClause(orderByClause);
			}
			List<ScBaseCvBrand> list = scBaseCvBrandMapper.selectByExample(example);
			return list;
		} catch (Exception e) {
			LOGGER.error("BrandServiceImpl.getAllList error : ", e);
			throw new BusinessException("查询网点异常");
		}
	}

	@Override
	public List<ScBaseCvBrand> selectAllBrand() throws Exception {
		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		ScBaseCvBrandExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		return scBaseCvBrandMapper.selectByExample(example);
	}

	@Override
	public Integer selectCountList(BrandQueryConditions conditions) {
		LOGGER.info("BrandServiceImpl.selectCountList params : {}, {}", conditions);

		if (null == conditions) {
			LOGGER.error("SeriesServiceImpl.selectCountList param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}

		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		ScBaseCvBrandExample.Criteria criteria = example.createCriteria();

		if (StringUtils.isNotBlank(conditions.getPrefix())) {
			criteria.andPrefixEqualTo(conditions.getPrefix());
		}
		if (StringUtils.isNotBlank(conditions.getName())) {
			criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
		}
		criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());

		return scBaseCvBrandMapper.countByExample(example);

	}

	@Override
	public List<ScBaseCvBrandDto> selectBrandSeriesModelByCondition(PageVo pageVo,
																	ScBrandSeriesModelBo scBrandSeriesModelBo) throws Exception {

		LOGGER.info("BaseBrandServiceImpl.selectBrandSeriesModelByCondition params : {}", scBrandSeriesModelBo);
		try {

			String orderByClause = null;
			if (null != pageVo) {
				orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder()
						: " brand.id DESC";
			}

			Map<String, Object> paramMap = new HashMap<>();
			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getBrandId()
					&& scBrandSeriesModelBo.getBrandId() > 0) {
				paramMap.put("brandId", scBrandSeriesModelBo.getBrandId());
			}

			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getModelId()
					&& scBrandSeriesModelBo.getModelId() > 0) {
				paramMap.put("modelId", scBrandSeriesModelBo.getModelId());
			}

			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getSeriesId()
					&& scBrandSeriesModelBo.getSeriesId() > 0) {
				paramMap.put("seriesId", scBrandSeriesModelBo.getSeriesId());
			}

			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getSeriesCode()
					&& "" != scBrandSeriesModelBo.getSeriesCode()) {
				paramMap.put("seriesCode", scBrandSeriesModelBo.getSeriesCode());
			}

			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getBrandCode()
					&& "" != scBrandSeriesModelBo.getBrandCode()) {
				paramMap.put("brandCode", scBrandSeriesModelBo.getBrandCode());
			}

			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getBrandName()
					&& "" != scBrandSeriesModelBo.getBrandName()) {
				paramMap.put("brandName", scBrandSeriesModelBo.getBrandName());
			}
			
			if (null != scBrandSeriesModelBo && null != scBrandSeriesModelBo.getModelCode()
					&& "" != scBrandSeriesModelBo.getModelCode()) {
				paramMap.put("modelCode", scBrandSeriesModelBo.getModelCode());
			}

			if (null != pageVo) {
				pageVo.setTotalRecord(scBaseBrandExpandMapper.countBrandSeriesModelByCondition(paramMap));
				paramMap.put("limitStart", pageVo.getStartIndex());
				paramMap.put("limitEnd", pageVo.getPageSize());
			}
			paramMap.put("orderByClause", orderByClause);
			paramMap.put("status", StatusEnum.NORMAL.getValue());
			return scBaseBrandExpandMapper.selectBrandSeriesModelByCondition(paramMap);

		} catch (Exception ex) {
			LOGGER.error("BaseBrandServiceImpl.selectBrandSeriesModelByCondition error:", ex);
		}

		return null;
	}

	/**
	 * 列表显示商品车数据
	 */
	@Override
	public ResultDTOWithPagination<List<ScBaseCvBrandDto>> findList(ScBaseCvBrandBO bo, PageVo vo) {
		LOGGER.info("ScBaseCvBrandServiceImpl.findList params : {},{}",bo, vo);
		ResultDTOWithPagination resultDTOWithPagination = new ResultDTOWithPagination<>(true, null, "查询成功");
		ScBaseCvBrandExample example = new ScBaseCvBrandExample();
		ScBaseCvBrandExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(bo.getName())) {
			criteria.andNameLike("%" + bo.getName() + "%");
		}
		if (StringUtils.isNotBlank(bo.getPrefix())) {
			criteria.andPrefixEqualTo(bo.getPrefix());
		}

		String orderByClause = null;
		if (null != vo) {
			orderByClause = StringUtils.isNotBlank(vo.getOrder()) == true ? vo.getOrder() : " id ASC";
		}
		// 查询总记录数
		int count = scBaseCvBrandMapper.countByExample(example);
		if (null != vo) {
			vo.setTotalRecord(count);
			example.setLimitEnd(vo.getPageSize());
			example.setLimitStart(vo.getStartIndex());
			example.setOrderByClause(orderByClause);
			resultDTOWithPagination.setPageVo(vo);
		}

		List<ScBaseCvBrand> list = scBaseCvBrandMapper.selectByExample(example);
		List<ScBaseCvBrandDto> list2 = new ArrayList<>();
		for (ScBaseCvBrand scBaseCvBrand : list) {
			ScBaseCvBrandDto scBaseCvBrand2 = new ScBaseCvBrandDto();
			BeanUtils.copyProperties(scBaseCvBrand, scBaseCvBrand2);
			list2.add(scBaseCvBrand2);
		}
		resultDTOWithPagination.setData(list2);

		return resultDTOWithPagination;
	}

	/**
	 * 新增商品车品牌
	 */
	@Override
	public void addScbasecvbrand(ScBaseCvBrandBO bo) {
		LOGGER.info("ScBaseCvBrandServiceImpl.addScbasecvbrand params : {}", bo);

		if (StringUtils.isBlank(bo.getCode())) {
			throw new BusinessException("品牌编码不能为空");
		}
		if (StringUtils.isBlank(bo.getName())) {
			throw new BusinessException("品牌名不能为空");
		}
		if (StringUtils.isBlank(bo.getPrefix())) {
			if (bo.getPrefix().length()>2){
				throw new BusinessException("品牌首字母太长");
			}
			throw new BusinessException("品牌首字母不能为空");
		}

		if (StringUtils.isBlank(bo.getStatus())) {
			throw new BusinessException("品牌状态不能为空");
		}

		ScBaseCvBrand scBaseCvBrand = new ScBaseCvBrand();
		BeanUtils.copyProperties(bo, scBaseCvBrand);
		scBaseCvBrand.setGmtCreate(new Date());
		scBaseCvBrand.setGmtModified(new Date());
		String firstSpell = pinyinUtil.getFirstSpell(scBaseCvBrand.getName());
		scBaseCvBrand.setInitialWords(firstSpell);
		scBaseCvBrand.setPinyin(pinyinUtil.getFullSpell(scBaseCvBrand.getName()));
		scBaseCvBrandMapper.insert(scBaseCvBrand);

	}

	/**
	 * 修改商品车品牌
	 */
	@Override
	public void updateScbasecvbrand(ScBaseCvBrandBO bo) {
		LOGGER.info("ScBaseCvBrandServiceImpl.updateScbasecvbrand params : {}", bo);

		ScBaseCvBrand brand = scBaseCvBrandMapper.selectByPrimaryKey(bo.getId());
		/*
		 * ScBaseCvBrand scBaseCvBrand = new ScBaseCvBrand();
		 * BeanUtils.copyProperties(bo, scBaseCvBrand);
		 */
		if (StringUtils.isNotBlank(bo.getCode())) {
			brand.setCode(bo.getCode());
		}
		if (StringUtils.isNotBlank(bo.getName())) {
			brand.setName(bo.getName());
		}
		if (StringUtils.isNotBlank(bo.getPrefix())) {
			brand.setPrefix(bo.getPrefix());
		}
		if (StringUtils.isNotBlank(bo.getStatus())) {
			brand.setStatus(bo.getStatus());
		}
		if (StringUtils.isNotBlank(bo.getBrandLogo())) {
			brand.setBrandLogo(bo.getBrandLogo());
			;
		}
		if (StringUtils.isNotBlank(bo.getComment())) {
			brand.setComment(bo.getComment());
		}
		String firstSpell = pinyinUtil.getFirstSpell(brand.getName());
		brand.setInitialWords(firstSpell);

		brand.setPinyin(pinyinUtil.getFullSpell(brand.getName()));
		brand.setGmtModified(new Date());
		scBaseCvBrandMapper.updateByPrimaryKey(brand);

	}

	@Override
	public void deleteScbasecvbrand(String ids) {
		LOGGER.info("ScBaseCvBrandServiceImpl.deleteScbasecvbrand params : {}", ids);

		if (StringUtils.isNotBlank(ids)) {
			String[] split = ids.split(",");
			for (String string : split) {
				int id = Integer.parseInt(string);
				ScBaseCvBrand brand = scBaseCvBrandMapper.selectByPrimaryKey(id);
				if(null!=brand&&null!=brand.getId()){
					brand.setStatus(BaseStatusEnum.DELETE.getValue());
					scBaseCvBrandMapper.updateByPrimaryKey(brand);
				}
			}
		} else {
			throw new BusinessException("商品车品牌id不能为空");
		}

	}

	@Override
	public ScBaseCvBrand getScbasecvbrandById(Integer id) {
		LOGGER.info("ScBaseCvBrandServiceImpl.getScbasecvbrandById params : {}", id);

		if (null == id || 0 == id) {
			throw new BusinessException("商品车品牌id不能为空");
		}
		ScBaseCvBrand brand = scBaseCvBrandMapper.selectByPrimaryKey(id);
		return brand;
	}

	@Override
	public List<BrandSeriesModel> getListByParam(PageVo pageVo, String cvKeyword) {
		LOGGER.info("ScBaseCvBrandServiceImpl.getListByParam params : {}, {}", pageVo, cvKeyword);

		if (null == cvKeyword) {
			LOGGER.error("ScBaseCvBrandServiceImpl.getListByParam param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}

		String orderByClause = null;
		Integer limitStart = null;
		Integer limitEnd = null;
		if (null != pageVo) {
			orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " se.id ASC";
			limitStart = pageVo.getStartIndex();
			limitEnd = pageVo.getPageSize();
		}

		List<BrandSeriesModel> list = scBaseCvBrandMapper.selectByCvKeyword(cvKeyword,orderByClause,limitStart,limitEnd);

		return list;
	}

	@Override
	public Integer selectCountListByParam(String cvKeyword) {

		LOGGER.info("ScBaseCvBrandServiceImpl.selectCountListByParam params : {}, {}", cvKeyword);
		if (null == cvKeyword) {
			LOGGER.error("ScBaseCvBrandServiceImpl.selectCountListByParam param cvKeyword must not be null  ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}
		return scBaseCvBrandMapper.countByCvKeyword(cvKeyword);
	}

}
